#!/usr/bin/env python

import re, sys, os

def parse ( txt, remap_cback = None ):
	split = re.compile ( r'(".*?"|\'.*?\'|=)|([a-zA-Z0-9_$]*)' )

	def _unquote ( txt ):
		if not txt: return ''
		if txt [ 0 ] in ( "'", '"' ): 
			txt = txt [ 1 : -1 ]

		res = [ x for x in txt.split ( "," ) if x ]

		output = []

		if remap_cback:
			for el in res:
				if el [ 0 ] == '$':
					output.append ( remap_cback ( el ) )
				else:
					output.append ( el )
		else:
			output = res

                return ','.join ( output ) 

	res = split.split ( txt )
	res = [ x.strip () for x in res if x and x.strip () ]

	#sys.stderr.write ( "------ RES: %s\n" % res )

	lst = []
	dct = {}

	count = 0

	while count < len ( res ):
		c = res [ count ]
		if count < len ( res ) -1:
			if res [ count + 1 ] == '=':
				dct [ c ] = _unquote ( res [ count + 2 ] )
				count += 2
			else:
				lst.append ( _unquote ( c ) )
		else:
			lst.append ( _unquote ( c ) )

		count += 1

	return lst, dct

if __name__ == '__main__':
	def my_remap ( txt ):
		dct = { "lang" : "it", "nome" : "fabio" }

		t = txt [ 1 : ]

		if not t in dct:
			return txt

		return dct [ t ]

	print parse ( "news test" )
	print parse ( 'news show tag="os3,$lang" pizza def="ciao" nome=$nome', my_remap )
	print parse ( 'ciao mamma nome=$nome pizza=$lang', my_remap )
